<?php
namespace Home\Controller;
use Think\Controller;
class ApiController extends Controller {


    public function index(){
        $this -> show('Hello API');
    }

//    public function initData() {
//        $model = M('t_report');
//        for ($i = 0; $i < 100; $i++) {
//            $newObj['assets'] = $i * 2237;
//            $newObj['liabilities'] = $i * 1052;;
//            $newObj['owners_equity'] = $newObj['assets'] + $newObj['liabilities'];
//            $result = $model -> add($newObj);
//        }
//        header("Access-Control-Allow-Origin: *");
//        return 'OK';
//    }

    public function getReports() {
        header("Access-Control-Allow-Origin: *");
        $model = M('t_report');
        $result = $model -> order('id') -> select();
        $this -> ajaxReturn($result);
    }

    public function addData() {
        $model = M('t_report');
        $newObj['assets'] = I('assets');
        $newObj['liabilities'] = I('liabilities');
        $newObj['owners_equity'] = I('owners_equity');
        $result = $model -> add($newObj);
        header("Access-Control-Allow-Origin: *");
        $this -> ajaxReturn($result);
    }

    public function deleteData() {
        $model = M('t_report');
        $id = I('id');
        $where['id'] = array('EQ', $id);
        $result = $model -> where($where) -> delete();
        header("Access-Control-Allow-Origin: *");
        $this -> ajaxReturn($result);
    }

    public function modifyData() {
        $model = M('t_report');
        $newObj['id'] = I('id');
        $newObj['assets'] = I('assets');
        $newObj['liabilities'] = I('liabilities');
        $newObj['owners_equity'] = I('owners_equity');
        $result = $model -> save($newObj);
        header("Access-Control-Allow-Origin: *");
        $this -> ajaxReturn($result);
    }

    public function addDatas() {
        $model = M('t_report');
        $datas = I('datas');
        for ($i = 0; $i < sizeof($datas); $i++) {
            $newObj = $datas[$i];
            $result = $model -> add($newObj);
        }
        header("Access-Control-Allow-Origin: *");
        $this -> ajaxReturn($result);
    }

    public function deleteDatas() {
        $model = M('t_report');
        $ids = I('ids');
        $result = 0;
        for ($i = 0; $i < sizeof($ids); $i++) {
            $id = $ids[$i];
            $where['id'] = array('EQ', $id);
            $itemResult = $model -> where($where) -> delete();
            $result += $itemResult;
        }
        header("Access-Control-Allow-Origin: *");
        $this -> ajaxReturn($result);
    }

    public function modifyDatas() {
        $model = M('t_report');
        $datas = I('datas');
        for ($i = 0; $i < sizeof($datas); $i++) {
            $newObj = $datas[$i];
            $result = $model -> save($newObj);
        }
        header("Access-Control-Allow-Origin: *");
        $this -> ajaxReturn($result);
    }
}